package com.heima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.heima.mapper.GoodsClassMapper;
import com.heima.mapper.GoodsMapper;
import com.heima.pojo.GoodsClassName;
import com.heima.pojo.GoodsInfo;
import com.heima.pojo.GoodsQueryParam;
import com.heima.pojo.PageBean;
import com.heima.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper ;
    @Autowired
    private GoodsClassMapper goodsClassMapper ;
    @Override
    public Boolean addGoods(GoodsInfo info) {
        GoodsInfo goods = new GoodsInfo();
        BeanUtils.copyProperties(info,goods);
        goods.setCreateTime(LocalDateTime.now());
        goods.setUpdateTime(LocalDateTime.now());
        if (goodsMapper.addGoods(goods)>1){
            return true;
        }
        return false;
    }

    @Override
    public PageBean Goodslist(GoodsQueryParam param) {
        //两个表，一个goods 一个goodsClass 先把class查了放进去，再查goods
        PageHelper.startPage(param.getPageIndex(), param.getPageSize());
        List<GoodsInfo> list = goodsMapper.getGoodslist(param);
        // 获取分页信息
        PageInfo<GoodsInfo> pageInfo = new PageInfo<>(list);



        for (GoodsInfo goodsInfo : list) {
            Integer classId = goodsInfo.getClassId();
            GoodsClassName goodsClass = goodsClassMapper.selectById(String.valueOf(classId));
            goodsInfo.setSkuClass(goodsClass);
        }
        //我如何获取 goodsClass中的内容？

        return new PageBean(
                param.getPageIndex(),
                param.getPageSize(),
                (long) pageInfo.getPages(), // 总页数
                pageInfo.getTotal(), // 总记录数
                pageInfo.getList()         // 当前页的数据列表
        );
    }

    @Override
    public Boolean upDateGoods(GoodsInfo goodsInfo, String skuId) {

        if(goodsMapper.selectGoodsName(goodsInfo.getSkuName()) != null){
            return false;
        }
        log.info("skuname是，{}",goodsInfo.getSkuName());
        goodsInfo.setSkuId(skuId);
        goodsMapper.updateGoods(goodsInfo);
        return true;
    }
}
